<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="教育集团名称" prop="edgroup_id">
        <el-select
          v-model="queryParams.edgroup_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
          @change="changeEdgroup(queryParams.edgroup_id, 'query')"
        >
          <el-option
            v-for="item in EdgroupList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="学校名称"
        prop="school_id"
        v-if="queryParams.edgroup_id"
      >
        <el-select
          v-model="queryParams.school_id"
          style="width: 200px"
          :filterable="true"
          :clearable="true"
        >
          <el-option
            v-for="item in schoolList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="班级名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="icon-search"
          clearable
          placeholder="请输入班级名称"
        >
          <template #suffix
            ><i class="el-icon-search el-input__icon"
          /></template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="classList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="序号" width="60" type="index" align="center"/> -->
      <el-table-column label="班级编号" min-width="80" align="center" prop="id" sortable/>
      <!-- show-overflow-tooltip -->
      <el-table-column
        label="教育集团名称"
        width="150"
        align="center"
        prop="school.edgroup.name"
        sortable
      >
        <template #default="scope">
          <el-tag v-if="scope.row?.school?.edgroup?.name" type="error">
            {{ scope.row?.school?.edgroup?.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="学校名称"
        show-overflow-tooltip
        align="center"
        prop="school.name"
        sortable
      >
        <template #default="scope">
          <el-tag v-if="scope.row?.school?.name" type="primary">
            {{ scope.row?.school?.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="班级名称"
        show-overflow-tooltip
        align="center"
        prop="name"
        sortable
      >
        <template #default="scope">
          <el-tag v-if="scope.row?.name" type="warning">
            {{ scope.row?.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="图片"
        show-overflow-tooltip
        align="center"
        prop="photo"
      >
        <template #default="scope">
          <span v-if="!scope.row.photo">暂无图片</span>
          <div v-else style="z-index: 10000">
            <el-image
              style="width: 50px; height: 20px"
              :src="scope.row.photo"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              hide-on-click-modal
              preview-teleported
              :preview-src-list="srcList"
              show-progress
              :initial-index="0"
              fit="cover"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        min-width="240"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Cellphone"
            @click="handleView(scope.row, 'gw')"
            >网关</el-button
          >
          <el-button
            link
            type="primary"
            icon="Cellphone"
            @click="handleView(scope.row, 'wb')"
            >手环</el-button
          >
          <el-button
            link
            type="primary"
            icon="Tools"
            @click="handleManage(scope.row)"
            >设备管理</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="ClassRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="教育集团名称" prop="school.edgroup.id">
          <el-select
            v-model="form.school.edgroup.id"
            placeholder="请选择教育集团"
            style="width: 260px"
            :filterable="true"
            :clearable="true"
            @change="changeEdgroup(form.school.edgroup.id, 'edit')"
          >
            <el-option
              v-for="edgroup in EdgroupList"
              :key="edgroup.value"
              :label="edgroup.label"
              :value="edgroup.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校名称" prop="school.id">
          <el-select
            v-if="schoolList.length > 0 && type == 'edit'"
            v-model="form.school.id"
            placeholder="请选择学校"
            style="width: 260px"
            :filterable="true"
            :clearable="true"
          >
            <el-option
              v-for="item in schoolList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            style="width: 260px"
            v-else
            disabled
            placeholder="该集团暂无学校"
          />
        </el-form-item>
        <el-form-item label="班级名称" prop="name">
          <el-input
            v-model="form.name"
            class="icon-search"
            clearable
            placeholder="请输入班级名称"
            style="width: 260px"
          >
            <template #suffix
              ><i class="el-icon-search el-input__icon"
            /></template>
          </el-input>
        </el-form-item>
        <el-form-item label="图片" prop="photo">
          <ImageUpload
            :limit="limit"
            list-type="picture-card"
            v-model="form.photo"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配网关对话框 -->
    <el-dialog :title="title" v-model="gw_open" width="800px" append-to-body>
      <el-row :gutter="20">
        <!-- 网关 -->
        <el-col :sm="24" :lg="24">
          <h3>
            <el-row :gutter="2" class="mb3"> </el-row>
          </h3>
          <el-table
            ref="tableRef"
            v-loading="gw_loading"
            height="auto"
            :data="gatewayLastList"
            @selection-change="handleSelectionGwChange"
            row-key="mac"
            :reserve-selection="true"
            empty-text="暂无分配网关"
          >
            <el-table-column type="selection" width="55" align="center" />
            <!-- <el-table-column
              label="序号"
              width="60"
              type="index"
              align="center"
            /> -->
            <el-table-column
              label="网关"
              align="center"
              prop="mac"
            />
            <el-table-column
              label="在线时间"
              align="center"
              prop="last_report_time"
            />
            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              width="280"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  icon="Sunrise"
                  @click="handleLight(scope.row, 'red')"
                  >红灯</el-button
                >
                <el-button
                  link
                  type="success"
                  icon="Sunrise"
                  @click="handleLight(scope.row, 'green')"
                  >绿灯</el-button
                >
                <el-button
                  link
                  type="primary"
                  icon="Sunrise"
                  @click="handleLight(scope.row, 'blue')"
                  >蓝灯</el-button
                >
                <el-button
                  link
                  type="warning"
                  icon="Bell"
                  @click="handleLight(scope.row)"
                  >蜂鸣</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="gw_last_total > 0"
            :total="gw_last_total"
            :small="true"
            v-model:page="gwLastQueryParams.pageNum"
            v-model:limit="gwLastQueryParams.pageSize"
            @pagination="getLastGateway"
          />
        </el-col>
      </el-row>
      <!-- <el-form
        ref="GatewayRef"
        :model="gw_form"
        :rules="gw_rules"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="网关地址" prop="name">
          <el-input
            v-model="form.name"
            class="icon-search"
            clearable
            placeholder="请输入网关地址"
            style="width: 260px"
          >
            <template #suffix
              ><i class="el-icon-search el-input__icon"
            /></template>
          </el-input>
        </el-form-item>
      </el-form> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmGw">分配</el-button>
          <el-button @click="cancelGw">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改学生对话框 -->
    <el-dialog :title="title" v-model="stu_open" width="500px" append-to-body>
      <el-form
        ref="StudentRef"
        :model="stu_form"
        :rules="stu_rules"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="姓名" prop="name">
          <el-input
            v-model="stu_form.name"
            class="icon-search"
            clearable
            placeholder="请输入学生姓名"
            style="width: 260px"
          >
            <template #suffix><i class="el-icon-search el-input__icon"/></template>
          </el-input>
        </el-form-item>
        <el-form-item label="学号" prop="s_number">
          <el-input
              v-model="stu_form.s_number"
              class="icon-search"
              clearable
              placeholder="请输入学生学号"
              style="width: 260px"
              >
            <template #suffix><i class="el-icon-search el-input__icon"/></template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormStu">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 分配手环 -->
    <el-dialog :title="title" v-model="wb_open" width="500px" append-to-body>
      <el-form
        ref="WbRef"
        :model="wb_form"
        :rules="wb_rules"
        label-width="120px"
        @submit.prevent
      >
        <el-form-item label="手环地址" prop="mac">
          <el-input
            v-model="wb_form.mac"
            class="icon-search"
            clearable
            placeholder="请输入手环地址"
            style="width: 260px"
          >
            <template #suffix
              ><i class="el-icon-search el-input__icon"
            /></template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormWb">确 定</el-button>
          <el-button @click="cancelWb">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设备管理 -->
    <el-dialog
      :title="manageTitle"
      v-model="manageOpen"
      width="90%"
      append-to-body
      class="dialog-device"
      :style="{ 
        height: dialogHeight + 'px',
        overflow: 'hidden' 
      }"
    >
      <el-row :gutter="20">
        <!-- 网关 -->
        <el-col :sm="12" :lg="12">
          <!-- <h3>
            <el-row :gutter="2" class="mb3">
              <el-col :span="1">
                <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="addGateway"
                  v-hasPermi="['system:post:add']"
                  >分配网关</el-button
                >
              </el-col>
              <div style="position: absolute; right: 20px">关联网关</div>
            </el-row>
          </h3> -->
          <div class="d-header">
            <div class="header-left">
              <span class="category-title">关联网关</span>
              <!-- <el-tag type="info"></el-tag> -->
            </div>
            <div class="header-right">
              <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="addGateway"
                  >分配网关</el-button
                >
            </div>
          </div>
          <el-table
            v-loading="loading"
            :data="gatewayList"
            border
            @selection-change="handleSelectionChange"
          >
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <!-- <el-table-column label="序号" width="60" type="index" align="center"/> -->
            <el-table-column
              label="网关"
              width="150"
              align="center"
              prop="mac"
            />
            <!--  -->
            <el-table-column
              label="网关"
              width="150"
              align="center"
              prop="last_report_time"
            >
              <template #default="scope">
                <el-tag v-if="isOnline(scope.row)" type="success">在线</el-tag>
                <el-tag v-else type="danger">未在线</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="danger"
                  icon="Sunrise"
                  @click="handleLight(scope.row, 'red')"
                  >红灯</el-button
                >
                <el-button
                  link
                  type="success"
                  icon="Sunrise"
                  @click="handleLight(scope.row, 'green')"
                  >绿灯</el-button
                >
                <el-button
                  link
                  type="primary"
                  icon="Sunrise"
                  @click="handleLight(scope.row, 'blue')"
                  >蓝灯</el-button
                >
                <el-button
                  link
                  type="warning"
                  icon="Bell"
                  @click="handleLight(scope.row)"
                  >蜂鸣</el-button
                >
                <el-button
                  link
                  type="primary"
                  icon="Tools"
                  @click="handleGwSetWb(scope.row)"
                  >批量分配手环</el-button
                >
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleGwSetWbName(scope.row)"
                  >批量写名字</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <!-- <pagination
            v-show="gw_total > 0"
            :total="gw_total"
            :page="gwQueryParams.pageNum"
            :limit="gwQueryParams.pageSize"
            @pagination="getGateway"
          /> -->
        </el-col>
        <!-- 学生 -->
        <el-col :sm="12" :lg="12">
          <!-- <h3>
            <el-row :gutter="2" class="mb3">
              <el-col :span="3">
                <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="addStudent"
                  v-hasPermi="['system:post:add']"
                  >新增</el-button
                >
              </el-col>
              <el-col :span="3">
                <el-button type="info" plain icon="Upload" @click="handleImport"
                  >导入</el-button
                >
              </el-col>
              <div style="position: absolute; right: 20px">关联学生</div>
            </el-row>
          </h3> -->
          <div class="d-header">
            <div class="header-left">
              <span class="category-title">关联学生</span>
              <el-form-item label="" prop="version">
                <el-input
                  v-model="stuQueryParams.version"
                  class="icon-search"
                  clearable
                  placeholder="请输入版本号"
                  style="width: 200px"
                  @input="getStudentWBList"
                >
                  <template #suffix><i class="el-icon-search el-input__icon"/></template>
                </el-input>
              </el-form-item>
              <!-- <el-tag type="info"></el-tag> -->
            </div>
            <div class="header-right">
              <el-button
                type="primary"
                plain
                icon="Plus"
                @click="addStudent"
                >新增</el-button>
              <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>
              <el-button type="danger" icon="Delete" plain @click="goClassStudents" :disabled="studentList.length==0">批量删除学生</el-button>
              <el-button type="danger" icon="Delete" plain @click="handleClears" :disabled="studentList.length==0">清空学生列表</el-button>
            </div>
          </div>
          <div :style="{height: dialogTableHeight + 'px'}" class="studentWbDetail">
            <el-table
              v-loading="loading"
              :data="studentList"
              :max-height="stu_total>0&&stu_total>stuQueryParams.pageSize?dialogTableHeight+'px':'auto'"
              border
              @selection-change="handleSelectionChange"
            >
              <!-- <el-table-column type="selection" width="55" align="center" /> -->
              <!-- <el-table-column label="序号" width="60" type="index" align="center"/> -->
              <!-- <el-table-column label="序号" width="60" prop="id" align="center"/> -->
              <el-table-column label="学号" width="120" prop="s_number" align="center"/>
              <el-table-column
                label="学生"
                align="center"
                prop="name"
              >
                <template #default="scope">
                  <span v-if="scope.row?.name.length">
                    {{ scope.row?.name.length > 2 ? scope.row?.name[0] + '*' +scope.row?.name.slice(-1) : scope.row?.name[0] + '*' }}
                  </span>
                  <span v-else>暂无姓名</span>
                </template>
              </el-table-column>
              <el-table-column
                label="关联手环"
                align="center"
                prop="student_wristband.mac"
              />
              <el-table-column
                label="手环版本号"
                align="center"
                prop="student_wristband.wristband.fw_version"
              />
              <el-table-column
                label="操作"
                fixed="right"
                align="center"
                width="160px"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="Switch"
                    v-if="scope.row.student_wristband"
                    @click="handleRemove(scope.row)"
                    >回收</el-button
                  >
                  <el-button
                    link
                    type="primary"
                    icon="Edit"
                    v-else
                    @click="handleUpWb(scope.row)"
                    >分配</el-button
                  >
                  <el-button
                    v-if="scope.row.student_wristband && gatewayList.length === 1"
                    link
                    type="primary"
                    icon="Edit"
                    @click="handleToMqtt(scope.row)"
                    >写名字</el-button>
                  <el-popover
                    placement="right"
                    width="400"
                    trigger="click">
                      <template #reference>
                        <el-button
                          link
                          type="primary"
                          icon="Edit"
                          v-if="scope.row.student_wristband && gatewayList.length > 1"
                          >写入名字</el-button>
                      </template>
                      <el-table
                        height="auto"
                        :data="gatewayList"
                        row-key="mac"
                        :reserve-selection="true"
                      >
                        <el-table-column align="center" prop="mac" label="网关"/>
                        <el-table-column
                          label="操作"
                          align="center"
                          class-name="small-padding fixed-width"
                        >
                          <template #default="sc">
                            <el-button
                              link
                              slot="reference"
                              type="primary"
                              icon="Edit"
                              @click="handleToMqtt(scope.row,sc.row.mac)"
                              >开始写名字</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                  </el-popover>
                  <el-button
                    link
                    type="danger"
                    icon="Delete"
                    v-if="!scope.row?.student_wristband?.mac"
                    @click="handleDelStudent(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="stu_total>0&&stu_total>stuQueryParams.pageSize"
              :total="stu_total"
              v-model:page="stuQueryParams.pageNum"
              v-model:limit="stuQueryParams.pageSize"
              :small="true"
              @pagination="getStudentWBList"
              style="max-width: 100%; margin: 0 auto"
            />
          </div>
          
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 学生导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="`${upload.url}?updateSupport=${upload.updateSupport}&class_id=${gw_form.class_id}`"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
      <!-- :action="`${upload.url}/${upload.updateSupport}/${gw_form.class_id}`" -->
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 批量删除学生对话框 -->
    <el-dialog :title="title" v-model="cStu_open" width="800px" append-to-body>
      <el-row :gutter="20">
        <!-- 学生 -->
        <el-col :sm="24" :lg="24">
          <h3>
            <el-row :gutter="2" class="mb3"> </el-row>
          </h3>
          <div class="classStudentList">
            <el-table
              ref="CStudentRef"
              v-loading="cStu_loading"
              height="auto"
              :data="cStudentList"
              @selection-change="handleSelectionCStuChange"
              row-key="id"
              :reserve-selection="true"
              empty-text="暂无学生列表"
            >
            <!-- :max-height="cStu_total>0&&cStu_total>cStuQueryParams.pageSize?dialogTableHeight+'px':'auto'" -->
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="学号" width="120" prop="s_number" align="center"/>
              <el-table-column
                label="学生"
                align="center"
                prop="name"
              />
              <el-table-column
                label="关联手环"
                align="center"
                prop="student_wristband.mac"
              />
            </el-table>

            <pagination
              v-show="cStu_total>0&&cStu_total>cStuQueryParams.pageSize"
              :total="cStu_total"
              v-model:page="cStuQueryParams.pageNum"
              v-model:limit="cStuQueryParams.pageSize"
              :small="true"
              @pagination="getClassStudents"
              style="max-width: 100%; margin: 0 auto"
            />
          </div>
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmCStu">确认删除</el-button>
          <el-button @click="cancelCStu">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 网关弹窗 -->
    <el-dialog title="网关管理" v-model="openGw" width="90%" append-to-body>
      <gateway 
        :edgroup_id="activeRow?.school?.edgroup?.id"
        :school_id="activeRow?.school?.id"
        :class_id="activeRow.id"
      />
    </el-dialog>

    <!-- 手环弹窗 -->
    <el-dialog title="手环管理" v-model="openWb" width="90%" append-to-body>
      <wristband 
        :edgroup_id="activeRow?.school?.edgroup?.id"
        :school_id="activeRow?.school?.id"
        :class_id="activeRow.id"
      />
    </el-dialog>
  </div>
</template>

<script setup name="Ota">
import { getFirmwaresList } from "@/api/system/user";
import { getType } from "@/api/system/dict/type";
import { getGatewayList } from "@/api/system/firmware/gateway";
import { getStudentList } from "@/api/system/school/student";
import { mqttOtaUpgrade } from "@/api/system/firmware/ota";
import { getToken } from "@/utils/auth";
import {
  getClassList,
  getClassById,
  updateClassById,
  createClass,
  deleteClassById,
  xbmConvert,
  getClassGwSetWb,
  getClassGwSetName,
  getClassGwControlLed,
  delCStudentByCId,
  delCStudentSelected,
  delCStudent
} from "@/api/system/school/class";
import { getSchoolList } from "@/api/system/school/school";
import { getEdgroupList } from "@/api/system/school/edgroup";
import {
  createStudentWristband,
  deleteStuWb,
  createStudent
} from "@/api/system/school/student";
import { getGatewayLastList, setGwClass } from "@/api/system/firmware/gateway";
import { reactive, onMounted, onBeforeUnmount } from "vue";
import gateway from "@/views/gateway/index.vue";
import wristband from "@/views/wristband/index.vue";
import { previewTable } from '@/api/tool/gen';
const { proxy } = getCurrentInstance();
const limit = ref(1);
const dialogHeight = ref(600);  // 设备管理 初始高度
const dialogTableHeight = ref(390);  // 设备管理 table 初始高度
const tableRef = ref(null); // el-table 的引用
const srcList = ref([]);
const type = ref("query");
const options = reactive({
  file: null, // 上传的固件文件
  filename: "firmware", // 默认文件名称
  outputType: "bin", // 默认输出文件类型（例如 .bin 或 .hex）
  previews: {}, // 预览数据（如果需要）
});
/*** 学生导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: true,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/student/importDataClass",
});
/** 导入按钮操作 */
function handleImport() {
  upload.title = "学生导入";
  upload.open = true;
}
function handleClears() {
  proxy.$modal
    .confirm('是否确认清空该班级学生列表的数据？')
    .then(function () {
      return delCStudentByCId(wb_form.value.class_id);
    })
    .then(() => {
      stuQueryParams.value.pageNum = 1
      stuQueryParams.value.pageSize = 15
      getStudentWBList({ class_id: wb_form.value.class_id })
      proxy.$modal.msgSuccess("清除学生列表成功");
    })
    .catch(() => {});
}
function handleDelStudent(row) {
  const sName = row.name
  proxy.$modal
    .confirm(`是否确认删除${row.name}该学生？`)
    .then(function () {
      return delCStudent(row.id);
    })
    .then(() => {
      stuQueryParams.value.pageNum = 1
      stuQueryParams.value.pageSize = 15
      getStudentWBList({ class_id: wb_form.value.class_id })
      proxy.$modal.msgSuccess(`删除学生：${sName}成功`);
    })
    .catch(() => {
      if (err === 'cancel') {
        proxy.$modal.msgInfo(`已取消删除学生：${sName}操作`);
      } else {
        proxy.$modal.msgError(`删除学生：${sName}失败，请稍后重试`);
      }
    });
}
/** 覆盖默认上传行为 */
function requestUpload() {}
const EdgroupList = ref();
getEdgroupList().then((res) => {
  EdgroupList.value = res.data.data.map((item) => {
    return {
      label: item.name,
      value: item.id,
      photo: item.photo,
    };
  });
});
getSchoolList().then((res) => {
  schoolList.value = res.data.data.map((item) => {
    return {
      label: item.name,
      value: item.id,
      photo: item.photo,
    };
  });
});
function changeEdgroup(e, val) {
  type.value = val;
  console.log("type", type.value);
  if (val == "query") {
    queryParams.value.school_id = null;
  }
  if (val == "edit") {
    form.value.school.edgroup.name = EdgroupList.value.find(
      (item) => item.value == e
    ).label;
    form.value.school.edgroup.photo = EdgroupList.value.find(
      (item) => item.value == e
    ).photo;
    form.value.school.id = null;
    form.value.school.name = undefined;
    form.value.school.photo = undefined;
  }
  schoolList.value = [];
  let params = {
    id: e,
  };
  getSchoolList(params).then((res) => {
    schoolList.value = res.data.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
        photo: item.photo,
      };
    });
  });
}
/** 上传预处理 */
function beforeUpload(file) {
  // 定义允许的固件文件格式
  const allowedFirmwareTypes = [".bin", ".hex"];
  const fileExtension = file.name
    .slice(file.name.lastIndexOf("."))
    .toLowerCase();

  // 校验文件格式
  if (!allowedFirmwareTypes.includes(fileExtension)) {
    proxy.$modal.msgError(
      "文件格式错误，请上传固件类型文件，如：.bin 或 .hex 后缀的文件。"
    );
    return false; // 阻止上传
  }

  // 校验文件大小（例如限制为 10MB）
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    proxy.$modal.msgError("文件大小超过限制，请上传小于 10MB 的文件。");
    return false; // 阻止上传
  }
  // 文件格式和大小都符合要求
  options.file = file; // 存储文件对象
  options.filename = file.name; // 存储文件名
  form.value.name = file.name;
  return true;
}
// console.log(firmware_type);
const schoolList = ref([]);
const classList = ref([]);
const firmwaresLists = ref([]);
const open = ref(false);
const gw_open = ref(false);
const stu_open = ref(false);
const loading = ref(true);
const gw_loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const gw_ids = ref([]);
const single = ref(true);
const gw_single = ref(true);
const multiple = ref(true);
const gw_multiple = ref(true);
const total = ref(0);
const title = ref("");
const manageTitle = ref("");
const dateRange = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: undefined,
    name: undefined,
  },
  rules: {
    name: [{ required: true, message: "班级名称不能为空", trigger: "blur" }],
    "school.edgroup.id": [
      { required: true, message: "教育集团名称不能为空", trigger: "blur" },
    ],
    "school.id": [
      { required: true, message: "学校名称不能为空", trigger: "blur" },
    ],
  },
});
const gw_last_data = reactive({
  gw_last_form: {},
  gwLastQueryParams: {
    pageNum: 1,
    pageSize: 10,
    class_id: undefined,
  },
  gw_last_rules: {},
});
const gw_data = reactive({
  gw_form: {},
  gwQueryParams: {
    pageNum: 1,
    pageSize: 10,
    class_id: undefined,
  },
  gw_rules: {
    mac: [{ required: true, message: "网关地址不能为空", trigger: "blur" }],
  },
});
const stu_data = reactive({
  stu_form: {},
  stuQueryParams: {
    pageNum: 1,
    pageSize: 15,
    class_id: undefined,
    version: undefined,
  },
  stu_rules: {
    name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  },
});
const wb_data = reactive({
  wbQueryParams: {},
  wb_form: {},
  wb_rules: {
    mac: [{ required: true, message: "手环地址不能为空", trigger: "blur" }],
  },
});

const cStudent_data = reactive({
  cStu_form: {},
  cStuQueryParams: {
    pageNum: 1,
    pageSize: 15,
    class_id: undefined,
  },
  cStu_rules: {
    name: [{ required: true, message: "学生不能为空", trigger: "blur" }],
  },
  cStu_ids: [],
  cStu_loading: false,
  cStu_open: false,
  cStudentList: [],
  cStu_total: 0,
  cStu_single: true,
  cStu_multiple: true
});
const { gwLastQueryParams, gw_last_form, gw_last_rules } = toRefs(gw_last_data);
const { queryParams, form, rules } = toRefs(data);
const { gwQueryParams, gw_form, gw_rules } = toRefs(gw_data);
const { stuQueryParams, stu_form, stu_rules } = toRefs(stu_data);
const { wbQueryParams, wb_form, wb_rules } = toRefs(wb_data);
const { cStuQueryParams, cStu_form, cStu_rules, cStu_ids, cStu_loading, cStu_open, cStudentList, cStu_total,cStu_single,cStu_multiple } = toRefs(cStudent_data);
const openGw = ref(false);
const openWb = ref(false);
const activeRow = ref({});
function rawChange(val) {
  if (!val) {
  }
}
function isOnline(row) {
  if(row?.online_time) return true;
  if (!row?.last_report_time) return false;
  const last = new Date(row.last_report_time.replace(/-/g, '/')).getTime();
  const now = Date.now();
  // 3分钟 = 180000 毫秒
  return now - last <= 180000;
}

/** 查询班级列表 */
function getList() {
  loading.value = true;
  classList.value = [];
  srcList.value = [];
  // console.log('queryParams.value', queryParams.value)
  getClassList(queryParams.value).then((response) => {
    console.log("班级列表", response.data.data);
    classList.value = response.data.data;
    classList.value.forEach((item) => {
      srcList.value.push(item.photo);
    });
    total.value = response.data.total;
    loading.value = false;
  });
}
/** 查询关联网关列表 */
function getGateway() {
  gatewayList.value = [];
  getGatewayList(gwQueryParams.value).then((response) => {
    console.log("关联网关列表", response.data.data);
    classList.value = response.data.data;
    classList.value.forEach((item) => {
      srcList.value.push(item.photo);
    });
    gw_total.value = response.data.total;
    gw_loading.value = false;
  });
}
/** 查询关联学生列表 */
function getStudent() {
  loading.value = true;
  classList.value = [];
  srcList.value = [];
  // console.log('queryParams.value', queryParams.value)
  getClassList(stuQueryParams.value).then((response) => {
    console.log("关联学生列表", response.data.data);
    classList.value = response.data.data;
    classList.value.forEach((item) => {
      srcList.value.push(item.photo);
    });
    stu_total.value = response.data.total;
    loading.value = false;
  });
}
// 分配网关
async function confirmGw() {
  console.log("选中分配", gw_ids.value);
  // 给班级分配多个网关（即网关-班级关联） 多对一
  let body = {
    class_id: gw_form.value.class_id,
    macList: gw_ids.value,
  };
  await setGwClass(body).then((res) => {
    console.log("分配成功", gw_form.value.class_id);
    getLastGateway();
    getGatewayList({ class_id: gw_form.value.class_id }).then((res) => {
      gatewayList.value = res.data.data;
      gw_total.value = res.data.total;
    });
    proxy.$modal.msgSuccess("分配成功");
    gw_open.value = false;
  });
}

// 取消分配
function cancelGw() {
  gw_open.value = false;
  reset_gw();
}


const manageOpen = ref(false);
const gw_total = ref(0);
const gatewayList = ref([]);
const gw_last_total = ref(0);
const gatewayLastList = ref([]);
const stu_total = ref(0);
const studentList = ref([]);
// 设备管理(弹窗)
async function handleManage(row) {
  try {
    console.log("设备管理。。。");
    // 使用 Promise.all 并行请求
    const [gatewayRes, studentRes] = await Promise.all([
      getGatewayList({ class_id: row.id }),
      getStudentList({ ...stuQueryParams.value, class_id: row.id}),
    ]);
    console.log("关联网关列表", gatewayRes?.data?.data || null);
    console.log("关联学生列表", studentRes?.data?.data|| null);
    // 处理响应
    gatewayList.value = gatewayRes?.data?.data || [];
    gw_total.value = gatewayRes?.data?.total || 0;
    studentList.value = studentRes?.data?.data || [];
    stu_total.value = studentRes?.data?.total || 0;
    // 确保数据已更新后再打开对话框
    await nextTick();
    manageOpen.value = true;
    gw_form.value.class_id = row.id;
    wb_form.value.class_id = row.id;
    stuQueryParams.value.class_id = row.id;
    cStuQueryParams.value.class_id = row.id;
    gwLastQueryParams.value.class_id = row.id;
    console.log("gw_form.value.class_id", gw_form.value.class_id);
    manageTitle.value = `${row?.school?.edgroup?.name ? row?.school?.edgroup?.name+'/':''}${row?.school?.name ? row?.school?.name+'/':''}${row.name} 设备管理`;
  } catch (error) {
    console.error("处理班级管理时出错:", error);
    // 可以在这里添加错误提示
  }
}
const wb_open = ref(false);
// 分配手环
function handleUpWb(row) {
  // 指定学生 id
  wb_form.value.sid = row.id;
  wb_open.value = true;
  title.value = "分配手环";
}
// 回收
function handleRemove(row) {
  // 回收关联的手环
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm("是否确认回收该手环？")
    .then(function () {
      return deleteStuWb({
        mac: row.student_wristband.mac,
        sid: row.id,
      });
    })
    .then(() => {
      getStudentWBList({ class_id: row.class.id })
      proxy.$modal.msgSuccess("回收成功");
    })
    .catch(() => {});
}

// 写入名字
function handleToMqtt(row, gw_mac) {
  // 添加弹窗指定网关 gw_mac(待写)
  // 指定网关写入名字
  if(gatewayList.value.length === 0) {
    proxy.$modal.msgError("请先添加网关");
    return;
  }
  let query = {
    name: row.name,
    gw_mac: gw_mac ? gw_mac : gatewayList.value[0].mac,
    wb_mac: row.student_wristband.mac,
  };
  console.log("query", query);
  xbmConvert(query).then((res) => {
    console.log("按学生写入名字 res", res);
    proxy.$modal.msgSuccess("名字写入成功");
  });
}

function handleLight(row, color) {
  if(!color){
    // 蜂鸣器操作
    proxy.$modal.msgError("蜂鸣器操作即将开放");
    return
  }
  console.log("闪灯 选择", row, color);
  const colorValue = color === 'red' ? {
    red: 1,// 0-255, 0:不亮, 255需转1因为硬件暂不支持
    green: 0,
    blue: 0,
  } : color === 'green' ? {
    red: 0,
    green: 1,
    blue: 0,
  } : color === 'blue' ? {
    red: 0,
    green: 0,
    blue: 1,
  } : {
    red: 1,
    green: 1,
    blue: 1,
  };
  console.log("闪灯 入参 ", {
    action: "led",
    gw_mac: row.mac,
    led1: colorValue});
  getClassGwControlLed({
    action: "led",
    gw_mac: row.mac,
    led1: colorValue,
  }).then((res) => {
    console.log("闪灯 res", res);
    proxy.$modal.msgSuccess("闪灯成功");
  });
}

/** 批量分配手环 按钮操作 */
function handleGwSetWb(row) {
  console.log("批量分配手环", row);
  proxy.$modal
    .confirm("是否确认批量分配手环？")
    .then(function () {
      return getClassGwSetWb({class_id: row.class.id, gw_mac: row.mac})
    })
    .then((res) => {
      const {code, msg} = res
      if(code !== 200) {
        proxy.$modal.msgError(msg || "批量分配手环失败");
        return;
      } else {
        proxy.$modal.msgSuccess(msg || "批量分配手环成功");
        getStudentWBList({ class_id: row.class.id })
      }
    })
    .catch((err) => {
      // console.log("批量分配手环 err", err);
      if (err === 'cancel') { // 判断是否是用户取消
        proxy.$modal.msgError('已取消操作');
      } else {
        // 其他错误处理
        // proxy.$modal.msgError(err||"批量分配手环失败");
      }
    });
}

/** 批量写姓名 按钮操作 */
function handleGwSetWbName(row) {
  console.log("批量写姓名", row);
  proxy.$modal
    .confirm("是否确认批量写姓名？")
    .then(function () {
      return getClassGwSetName({class_id: row.class.id, gw_mac: row.mac})
    })
    .then(() => {
      getStudentWBList({ class_id: row.class.id })
      proxy.$modal.msgSuccess("开始批量写姓名");
    })
    .catch(() => {
      proxy.$modal.msgError("批量写姓名失败");
    });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  type.value = "edit";
  const id = row.id || ids.value;
  console.log("id", id);
  getClassById(id).then((response) => {
    console.log(response.data);
    form.value = response.data;
    let params = {
      id: form.value.school.edgroup.id,
    };
    getSchoolList(params).then((res) => {
      schoolList.value = res.data.data.map((item) => {
        return {
          label: item.name,
          value: item.id,
          photo: item.photo,
        };
      });
    });
    open.value = true;
    title.value = "修改班级";
  });
}

function handleView(row, type) {
  activeRow.value = row;
  console.log("查看操作", activeRow.value, type);
  if (!ids) {
    proxy.$modal.msgError("请选择要查看的学校");
    return;
  }
  switch (type) {
    case "gw":
      openGw.value = true;
      break;
    case "wb":
      openWb.value = true;
      break;
    default:
      proxy.$modal.msgError("未知操作类型");
      break;
  }
}
// 固件列表
function getFirmwaresLists() {
  getFirmwaresList().then((response) => {
    // console.log("固件列表",response);
    const { data, msg, code } = response;
    if (code === 200) {
      firmwaresLists.value = data;
    } else {
      firmwaresLists.value = [];
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
function cancelWb() {
  wb_open.value = false;
  reset_wb();
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    name: "", //
    photo: "",
    school: {
      id: null,
      name: undefined,
      photo: undefined,
      edgroup: {
        id: null,
        name: undefined,
        photo: undefined,
      },
    },
  };
  proxy.resetForm("ClassRef");
}

// 重置关联网关
function reset_gw() {
  gw_form.value.mac = "";
  gw_form.value.id = undefined;
  proxy.resetForm("GatewayRef");
}

// 重置 班级学生
function reset_c_student() {
  cStu_form.value.mac = "";
  cStu_form.value.id = undefined;
  proxy.resetForm("CStudentRef");
}

// 重置关联学生
function reset_stu() {
  stu_form.value = {
    id: undefined,
    name: "",
    s_number: "",
  };
  proxy.resetForm("StudentRef");
}

function reset_wb() {
  wb_form.value.mac = "";
  proxy.resetForm("WbRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 网关多选选择数据
function handleSelectionGwChange(selection) {
  gw_ids.value = selection.map((item) => item.mac);
  gw_single.value = selection.length != 1;
  gw_multiple.value = !selection.length;
  console.log("gw_ids.value", gw_ids.value);
}

// 班级学生多选择数据
function handleSelectionCStuChange(selection) {
  cStu_ids.value = selection.map((item) => item.id);
  cStu_single.value = selection.length != 1;
  cStu_multiple.value = !selection.length;
  console.log("班级学生多选择数据 cStu_ids.value", cStu_ids.value);
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // console.log('form.value', form.value )
  open.value = true;
  title.value = "新增班级";
}
function getLastGateway() {
  gw_ids.value = [];
  getGatewayLastList(gwLastQueryParams.value).then((res) => {
    console.log("近期活跃的网关", res);
    gatewayLastList.value = res.data.data;
    gw_last_total.value = res.data.total;
    console.log("gw_form.value.class_id", gw_form.value.class_id);
    // 数据加载完成后，设置默认选中的行
    nextTick(() => {
      gatewayLastList.value.forEach((item) => {
        console.log("item", item);
        if (item?.class?.id == gw_form.value.class_id) {
          tableRef.value.toggleRowSelection(item, true);
          gw_ids.value.push(item.mac);
          console.log("gw_ids.value", gw_ids.value);
        }
        gw_loading.value = false;
      });
    });
  });
}

function getClassStudents() {
  const paramsData = {
    ...cStuQueryParams.value
  }
  getStudentList(paramsData).then((res) => {
    console.log("获取班级所有学生》》》", res.data.data);
    cStudentList.value = res.data.data;
    cStu_total.value = res.data.total;
    console.log("cStu_form.value.class_id", cStu_form.value.class_id);
    // 数据加载完成后，设置默认选中的行
    // nextTick(() => {
    //   gatewayLastList.value.forEach((item) => {
    //     console.log("item", item);
    //     if (item?.class?.id == gw_form.value.class_id) {
    //       tableRef.value.toggleRowSelection(item, true);
    //       gw_ids.value.push(item.mac);
    //       console.log("gw_ids.value", gw_ids.value);
    //     }
    //     gw_loading.value = false;
    //   });
    // });
  });
}
/** 新增关联网关按钮操作 */
async function addGateway() {
  gw_loading.value = true;
  reset_gw();
  // console.log('form.value', form.value )
  gw_open.value = true;
  title.value = "分配网关";
  // 查询网关表（按照updatetime获取近5分钟的）
  await getLastGateway();
  gw_loading.value = false;
}

/** 批量删除学生 操作 */
async function goClassStudents() {
  cStu_loading.value = true;
  reset_c_student();
  // console.log('cStu_form.value', cStu_form.value )
  cStu_open.value = true;
  title.value = "批量删除学生";
  cStu_ids.value = [];
  // 查询班级所有学生
  await getClassStudents();
  cStu_loading.value = false;
}

// 批量删除学生 按钮
async function confirmCStu() {
  console.log("批量删除学生", cStu_ids.value);
  await delCStudentSelected({ids: cStu_ids.value}).then((res) => {
    console.log("批量删除学生成功", gw_form.value.class_id);
    getStudentWBList({ class_id: wb_form.value.class_id })
    proxy.$modal.msgSuccess("批量删除学生成功");
    cStu_open.value = false;
  });
}

// 取消 批量删除学生
function cancelCStu() {
  gw_open.value = false;
  reset_gw();
}

/** 新增关联学生按钮操作 */
function addStudent() {
  reset_stu();
  // console.log('form.value', form.value )
  stu_open.value = true;
  title.value = "新增关联学生";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ClassRef"].validate((valid) => {
    if (valid) {
      console.log(111, form.value.id);
      form.value.school.name = schoolList.value.find(
        (item) => item.value == form.value.school.id
      ).label;
      form.value.school.photo = schoolList.value.find(
        (item) => item.value == form.value.school.id
      ).photo;
      if (form.value.id != undefined) {
        console.log(form.value);
        updateClassById(form.value).then((response) => {
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("修改失败");
          }
        });
      } else {
        console.log("add", form.value);
        createClass(form.value).then((response) => {
          // console.log(response);
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          } else {
            proxy.$modal.msgError("新增失败");
          }
        });
      }
    }
  });
}
// 提交手环分配(只有回收了才有分配)
function submitFormWb() {
  proxy.$refs["WbRef"].validate((valid) => {
    if (valid) {
      console.log("add", wb_form.value);
      createStudentWristband(wb_form.value).then((response) => {
        // console.log(response);
        const { code, data, msg } = response;
        if (code === 200) {
          proxy.$modal.msgSuccess("新增成功");
          wb_open.value = false;
          getStudentWBList({ class_id: wb_form.value.class_id })
        } else {
          proxy.$modal.msgError("新增失败");
        }
      });
    }
  });
}

// 提交新增学生 
function submitFormStu() {
  proxy.$refs["StudentRef"].validate((valid) => {
    if (valid) {
      console.log(111, stu_form.value.id);
      if (stu_form.value.id != undefined) {
        console.log('update stu_form', stu_form.value);
        updateStudentById(stu_form.value).then((response) => {
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("修改姓名成功");
            stu_open.value = false;
            getStudentWBList({ class_id: wb_form.value.class_id })
          } else {
            proxy.$modal.msgError("修改姓名失败");
          }
        });
      } else {
        console.log("add stu_form", stu_form.value);
        createStudent({...stu_form.value, class:{id: wb_form.value.class_id}}).then((response) => {
          // console.log(response);
          const { code, data, msg } = response;
          if (code === 200) {
            proxy.$modal.msgSuccess("新增学生成功");
            stu_open.value = false;
            getStudentWBList({ class_id: wb_form.value.class_id })
          } else {
            proxy.$modal.msgError("新增学生失败");
          }
        });
      }
    }
  });
}

/** 获取学生和手环关系表 */
function getStudentWBList(params) {
  const paramsData = !params ? {
    ...stuQueryParams.value
  }:{
    ...stuQueryParams.value,
    ...params,
  };
  getStudentList(paramsData).then((res) => {
    console.log("获取学生和手环关系表", res.data.data);
    studentList.value = res.data.data;
    stu_total.value = res.data.total;
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除编号为"' + ids + '"的数据项？')
    .then(function () {
      return deleteClassById(ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 修改操作 */
function handleEdit(row) {
  const params = {
    taskId: row.id,
    schoolid: row.schoolid,
    localPath: row.path,
    force: row.force || false,
  };
  proxy.$modal
    .confirm(`是否现在升级任务编号为 ${row.id} 的任务？`)
    .then(function () {
      return mqttOtaUpgrade(params);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("开始升级");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  /*proxy.download("system/post/export", {
    ...queryParams.value
  }, `post_${new Date().getTime()}.xlsx`);*/
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("/student/importTemplateClass", {
  }, `student_template_${new Date().getTime()}.xlsx`);
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getStudentWBList({ class_id: wb_form.value.class_id })
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

function customUpload(params) {
    const file = params.file;
    const url = params.action; // 已包含参数的完整 URL

    // 创建 FormData（虽然 GET 通常不传 body，但保留用于极端情况）
    const formData = new FormData();
    formData.append('file', file);

    // 使用 axios 发送 GET 请求
    // axios.(url, {
    //   params: {

    //     // 附加额外参数（如果需要）
    //   },
    //   headers: {
    //     ...this.upload.headers,
    //     'Content-Type': 'multipart/form-data' // GET 请求一般不设置此类型
    //   }
    // })
    // .then(response => {
    //   this.handleFileSuccess(response, file);
    // })
    // .catch(error => {
    //   // 处理错误
    // });
  }

//** 计算对话框高度 **/
function calcDialogHeight() {
  // 计算高度为窗口高度的 80%，最小高度 600px，最大高度 90%
  const minH = 600;
  const maxH = window.innerHeight * 0.9;
  dialogHeight.value = Math.min(
    Math.max(window.innerHeight * 0.8, minH),
    maxH
  );
  dialogTableHeight.value = dialogHeight.value - 200;
}

getFirmwaresLists();
getList();

onMounted(() => {
  // 窗口变化时更新对话框高度
  window.addEventListener('resize', calcDialogHeight);
  calcDialogHeight();
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', calcDialogHeight);
})

</script>

<style lang="scss" scoped>
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
/* 自定义头部容器 */
.d-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 0 0 10px 0; /* 覆盖默认 padding */
}

/* 左侧分类名称样式 */
.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
  :deep(.el-form-item--default){
    margin-bottom: 0;
  }
}
.category-title {
  font-size: 1.17em;
  color: #606266;
  font-weight: bold;
}

/* 右侧按钮组样式 */
.header-right {
  display: flex;
  // gap: 5px; /* 按钮间距 */
  margin-left: auto;  /* 右侧贴边 */
  padding-right: 0;   /* 清除右侧内边距 */
}
.studentWbDetail, .classStudentList {
  :deep(.pagination-container .el-pagination) {
    right: 20px;
  }
}
</style>
